<template>
  <div>
    <!-- 列表 -->
    <DataTable :list="menuList" :fields="fields" v-loading="listLoading"
      :permissions="$store.state.permissions" :add="toSave" :exports="toSave"
      children="childMenus" :edit="toSave" :del="del">
      <slot slot="beforeButtonSlot" slot-scope="scope">
        <el-tooltip v-if="$store.state.permissions.insert" content="新增子菜单" class="operatingButton">
          <el-link type="primary" icon="el-icon-circle-plus-outline" v-if="scope.row.menuType == 0"
            :underline="false" @click="toSaveByParent(scope.row)">
          </el-link>
        </el-tooltip>
      </slot>
    </DataTable>

    <!-- 新增&修改 表单 -->
    <!-- <Form :title="title" :visible.sync="visible" :fields.sync="fromFields" :formData="form" :submitForm="submitForm">
    </Form> -->
    <el-dialog :title="title" :visible.sync="visible" width="60%" :before-close="cancel" :destroy-on-close="true"
      :close-on-click-modal="false">
      <el-form ref="form" :model="form" label-width="12%" :rules="rules">
        <el-form-item label="父级菜单" prop="parentId">
          <el-cascader v-model="form.parentId" :options="parentMenuOptions"
            placeholder="请选择父级菜单" :show-all-levels="false" :props="{ emitPath: false, checkStrictly: true }" />
        </el-form-item>

        <el-form-item label="菜单类型" prop="menuType">
          <el-radio v-model="form.menuType" :label="0" border>菜单</el-radio>
          <el-radio v-model="form.menuType" :label="1" border>按钮</el-radio>
        </el-form-item>
        
        <el-form-item v-if="form.menuType == 0" label="菜单名称" prop="menuName" >
          <el-input v-model="form.menuName" size="small" placeholder="请输入菜单名称"></el-input>
        </el-form-item>
        
        <el-form-item v-else label="按钮名称" prop="menuName" >
          <el-select v-model="form.menuName" placeholder="请选择按钮名称" size="small">
            <el-option
              v-for="item in buttonNameOptions"
              :key="item.label"
              :label="item.label"
              :value="item.label">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="菜单图标" prop="menuIcon" v-if="form.menuType==0" >
          <el-input v-model="form.menuIcon" placeholder="请选择菜单图标" :disabled="true">
            <template slot="prepend">
              <p class="menu_icon_box" v-html="form.menuIcon"></p>
            </template>
            <template slot="append">
              <el-button @click="iconSelectorDisplay = true">选择图标</el-button>
            </template>
          </el-input>
          <IconSelector :visible.sync="iconSelectorDisplay" :value.sync="form.menuIcon"/>
        </el-form-item>

        <el-form-item label="菜单路由" prop="menuRouter" v-if="form.menuType==0">
          <el-input v-model="form.menuRouter" size="small" placeholder="请输入菜单路由（注：拥有子菜单时路由失效）" 
          ></el-input>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" />
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button :loading="saveLoading" type="primary" @click="submitForm">提 交</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
const DataTable = () => import("@/views/Common/DataTable/haveChildren.vue");
const IconSelector = () => import("@/views/Common/Form/iconSelector.vue");

export default {
  name: "Menu",
  components: { DataTable, IconSelector },
  data() {
    return {
      // 表单标题
      title: "",
      // 表单显示状态
      visible: false,
      // 提交按钮加载状态
      confirmLoading: false,
      // 图标选择器显示状态
      iconSelectorDisplay: false,
      // 列表字段
      fields: [
        {
          label: "菜单名称",
          value: "menuName"
        },
        {
          label: "菜单图标",
          value: "menuIcon",
          type: "icon"
        },
        {
          label: "菜单类型",
          value: "menuType",
          type: "dict",
          dict:[
            {
              label:"菜单",
              value:"0"
            },
            {
              label:"按钮",
              value:"1"
            }
          ]
        },
        {
          label: "菜单路由",
          value: "menuRouter",
        },
        {
          label: "排序",
          value: "sort",
        },
      ],
      // 列表数据
      menuList: [],
      listLoading: false,
      // 表单字段
      saveLoading: false,
      rules:{
        parentId: [{ required: true, message: "父级菜单不能为空!" }],
        menuName: [{ required: true, message: "菜单名称不能为空!" }],
        menuType: [{ required: true, message: "菜单类型不能为空!" }],
      },
      parentMenuOptions: [],
      // 表单参数
      form: {},
      buttonNameOptions: [],
    };
  },
  watch: {
    "$store.state.dict.menu_button_name":{
      handler(value){
        if(value){
          let buttonNameOptions = [];
          Object.keys(value).forEach(e=>{
            buttonNameOptions.push({
              label: e,
              value: value[e]
            })
          })
          this.buttonNameOptions = buttonNameOptions;
        }
      }
    }
  },
  created(){
    let value = this.$store.state.dict.menu_button_name;
    if(value){
      let buttonNameOptions = [];
      Object.keys(value).forEach(e=>{
        buttonNameOptions.push({
          label: e,
          value: value[e]
        })
      })
      this.buttonNameOptions = buttonNameOptions;
    }
  },
  mounted() {
    this.getMenuList();
  },
  methods: {
    // 关闭事件
    cancel() {
      this.visible = false;
      this.$nextTick(() => {
        this.$refs["form"].resetFields();
      });
    },
    // 打开 新增/修改 表单
    toSave(menuId) {
      this.form = {
        menuType: 0,
        sort: 0
      };
      if (menuId) {
        this.title = "修改菜单";
        this.$api.menu.getOne(menuId).then((res) => {
          this.form = res.data;
        });
      } else {
        this.title = "新增菜单";
      }
      this.visible = true;
    },
    toSaveByParent(row) {
      this.form = {
        parentId: row.uuid,
        menuType: 0,
        sort: 0
      };
      this.title = "新增菜单";
      this.visible = true;
    },
    // 提交表单
    submitForm() {
      this.saveLoading = true;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.uuid != this.form.parentId) {
            this.$api.menu.save(this.form).then((res) => {
              if (res.code == 200) {
                this.visible = false;
                this.saveLoading = false;
                this.getMenuList();
                this.$emit('getMenuTree');
                this.$message.success(res.msg);
              } else {
                this.saveLoading = false;
                this.$message.error(res.msg);
              }
            });
          } else {
            this.saveLoading = false;
            this.$message.warning("父级菜单不能与当前菜单相同！");
          }
        }else{
          this.saveLoading = false;
        }
      });
      
    },
    // 删除
    del(menuId) {
      this.$api.menu.del({ uuid: menuId }).then((res) => {
        if (res.code == 200) {
          this.getMenuList();
          this.$emit('getMenuTree');
          this.$message.success("删除成功");
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    // 获取列表
    getMenuList() {
      this.listLoading = true;
      this.$api.menu.getList().then((res) => {
        if (res.code == 200) {
          this.menuList = res.data;
          this.parentMenuOptions = [
            {
              value: "0",
              label: "主类目",
              children: this.buildOptions(this.menuList),
            },
          ];
        } else {
          this.$message.error(res.msg);
        }
        this.listLoading = false;
      });
    },
    // 构建联级选择数据
    buildOptions(menuList) {
      let list = [];
      menuList.forEach((e) => {
        let options = {};
        options["value"] = e.uuid;
        options["label"] = e.menuName;
        if (e.childMenus && e.childMenus.length != 0) {
          options["children"] = this.buildOptions(e.childMenus);
        }
        list.push(options);
      });
      return list;
    },
  },
};
</script>

<style lang="less">
.menu_icon_box{
  height: 23px;
  svg{
    width: 23px;
    height: 23px;
  }
}
</style>